package com.mbl.base.modular.trademark.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.utils.UtilEasyPoi;
import com.mbl.base.modular.trademark.entity.Library;
import com.mbl.base.modular.trademark.entity.excelVo.ExcelLibrary;
import com.mbl.base.modular.trademark.service.ILibraryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mbl.base.core.common.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商标数据库（保存所有的商标信息） 前端控制器
 * </p>
 *
 * @author lwj
 * @since 2020-05-15
 */
@RestController
@RequestMapping("/trademark/library")
public class LibraryController extends BaseController<Library, ILibraryService> {

    @PostMapping("/importAll")
    public MblResult importAll(@RequestParam("file") MultipartFile file) throws IOException {
        final List<ExcelLibrary> libraries = UtilEasyPoi.importExcel(file, ExcelLibrary.class);
        List<Library> librariesList = new ArrayList<>();
        libraries.forEach(library -> {
            library.setDateOfApplication(library.getDateOfApplicationVo().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            library.setAnnouncementDate(library.getAnnouncementDateVo().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            final Date registrationAnnouncementDateVo = library.getRegistrationAnnouncementDateVo();
            if(registrationAnnouncementDateVo != null){
                library.setRegistrationAnnouncementDate(registrationAnnouncementDateVo.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
            final String goodsService = library.getGoodsService();
            if(StringUtils.isNotBlank(goodsService)){
                final String[] lin = goodsService.split(";");
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < lin.length; i++) {
                    JSONObject jsonObject = new JSONObject();
                    final String[] split = lin[i].split("----");
                    jsonObject.put(split[0], split[1]);
                    jsonArray.add(jsonObject);
                }
                library.setGoodsService(jsonArray.toJSONString());
            }
            librariesList.add(library);
            try {
                library.insert();
            }catch (Exception e){

            }

        });
        return MblResult.success();
    }



}

